/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package x10.interfaces.cm15a.transmit;

import java.util.logging.Logger;

import x10.event.X10Command;
import x10.event.X10Event;
import x10.queues.X10TransmitQueue;
import x10.utilities.ChunkOfBytes;

/**
 *
 * @author Denny
 */
public class PLCommandFactory extends X10DeviceTransmitter {
    Logger logger = Logger.getLogger(this.getClass().getName());

    X10Command plCommand;
    public PLCommandFactory(X10TransmitQueue transmitQueue){
        super(transmitQueue);
    }
    
    public void transmit(X10Event device){
        try{
            plCommand = (X10Command)device;
        } catch (Exception e){
            logger.warning("Unable to cast X10Device to X10Command (Powerline)");
            e.printStackTrace();
        }

        byte[] bytes = new byte[2];

        //Transmit address command
        bytes[0] = getAddressHeader();
        bytes[1] = getAddress(plCommand);

        ChunkOfBytes chunk = new ChunkOfBytes();
        chunk.setBytes(bytes);
        chunk.setLength(2);
        chunk.setEmpty(false);

        transmitQueue.put(chunk);

        //Transmit function command
        bytes[0] = getFunctionHeader();
        bytes[1] = getFunction(plCommand);

        chunk.setBytes(bytes);
        chunk.setLength(2);
        chunk.setEmpty(false);
        
        transmitQueue.put(chunk);

    }

    private byte getAddressHeader(){
        return (byte) 0x04; //Powerline Address Header
    }

    private byte getFunctionHeader(){
        return (byte) 0x06; //Powerline Function Header
    }


    private byte getAddress(X10Command command){
        byte house = command.getHouseCode().getPowerlineHouseCodeInUpperNibble();
        byte device = command.getDeviceCode().getPowerlineVersion();
        return (byte) (house | device);
    }

    private byte getFunction(X10Command command){
        byte house = command.getHouseCode().getPowerlineHouseCodeInUpperNibble();
        byte function = command.getFunctionCode().getByteValue();
        return (byte) (house | function);
    }

}
